/**
 *
 * ajax({
 *  method: 'post',
 *  url: 'url',
 *  data: {
 *
 *  }
 * }).then(res=>{
 *
 * })
 *
 * **/

export async function ajax(params) {
  const {
    url, method, data
  } = params;
  let Api = '';
  if (process.env.NODE_ENV === 'development') {
    Api = '/devApi'
  } else {
    Api = ''
  }

  if (method === 'GET' || method === 'get') {
    let params = '';
    if (data) {
      for (let k in data) {
        params = params + `&${k}=${data[k]}`;
      }
      params = '?' + params.substring(1, params.length);
    }
    return fetch(Api + url + params, {
      method: 'GET',
      credentials: 'include',
    }).then((res) => {
      return res.json()
    }).catch((e) => {
      return e
    })
  } else if (method === 'POST' || method === 'post') {
    // console.log(data);
    let params = '';
    if (data) {
      for (let k in data) {
        // console.log(k, data[k]);
        params = params + `&${k}=${data[k]}`;
      }
      params = params.substring(1, params.length);
    }
    return fetch(Api + url, {
      method: 'POST',
      credentials: 'include',
      headers: {
        'Accept': '*/*',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      },
      body: params
    }).then((res) => {
      return res.json()
    }).catch((e) => {
      return e
    })
  }
}